<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Company extends Model
{
    use SoftDeletes;

    protected $table  = 'companies';
    protected $hidden = ['pivot'];

    const STATUS = [
        0 => '待审核',
        1 => '通过',
        2 => '拒绝',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联关系 N:N 查询公司下面所有的用户
     * @return BelongsToMany
     */
    public function users(): BelongsToMany
    {
        //参数1:要去关联的类   参数2:中间表  参数3:中间表里本类id   参数4:中间表里关联类的id    参数5:本类主键id   参数6:关联类主键id
        return $this->belongsToMany(User::class, 'company_user', 'company_id', 'user_id')->withPivot('creator_id', 'is_admin'); //获取中间表字段
    }

    /**
     * 关联关系 1:N 查询公司下的部门
     * @return HasMany
     */
    public function departments(): HasMany
    {
        return $this->hasMany(Department::class)->select(['id','title','company_id','project_id','department_id', 'part_company_id']);
    }

    /**
     * 关联关系 1:N 查询公司下的项目
     * @return HasMany
     */
    public function projects(): HasMany
    {
        return $this->hasMany(Project::class)->select(['id', 'company_id', 'title', 'document_number']);
    }

    /**
     * 委托人，授权人，每个公司的公司总管理员
     * 参数1:要去关联的类   参数2:中间表  参数3:中间表里本类id   参数4:中间表里关联类的id
     */
    public function principal(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'company_user', 'company_id', 'user_id')
            ->wherePivot('is_admin', 1)
            ->withPivot(['is_admin']);
    }

    /**
     * 获取公司下的角色
     * @return HasMany
     */
    public function roles()
    {
        return $this->hasMany(Role::class)->select(['id', 'title', 'company_id']);
    }

}
